#include <iostream>

#include "common_list.h"

using namespace std;

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param pHead ListNode类
     * @param k int整型
     * @return ListNode类
     */
    ListNode *FindKthToTail(ListNode *pHead, int k) {
        if (!pHead)
            return nullptr;
        auto fast = pHead;
        auto slow = pHead;
        while(k > 1) {
            fast = fast->next;
            if (fast == nullptr)
                return nullptr;
            k--;
        }

        while(fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }
};

int main() {
    cout << " 链表中倒数最后k个结点" << endl;
    auto head = generate_list(2);
    auto k_node = (new Solution())->FindKthToTail(head, 1);
    print_list(head);
    if (k_node)
        cout << "Kth node val: " << k_node->val << endl;
    else
        cout << "nullptr" << endl;
    return 0;
}